﻿using Sirenix.OdinInspector;
using Sirenix.Utilities;
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

namespace Framework
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class InvokeOnStage : Attribute
    {
        private string stage;
        public InvokeOnStage(string stage)
        {
            this.stage = stage;
        }
        public string Stage { get => stage; }
    }

    public static class InvokStageManager
    {
        static Dictionary<string, List<Action>> actions = new();

        public static void InvokStage(string stage)
        {
            if (actions.TryGetValue(stage, out List<Action> action))
            {
                foreach (var act in action)
                {
                    act?.Invoke();
                }
            }
            else
            {
                Debug.LogWarning($"stage:{stage} has no function to call");
            }
        }

        static InvokStageManager()
        {
            ReloadStageInvoker();
        }

        public static void ReloadStageInvoker()
        {
            Assembly assembly = Assembly.GetAssembly(typeof(InvokStageManager));
            var types = assembly.GetExportedTypes();
            foreach (var type in types)
            {
                foreach (var function in type.GetMethods())
                {
                    InvokeOnStage invokAtr = function.GetCustomAttribute(typeof(InvokeOnStage)) as InvokeOnStage;
                    if (invokAtr == null)
                    {
                        continue;
                    }

                    if (actions.TryGetValue(invokAtr.Stage, out List<Action> action))
                    {
                        action.Add(() => { function.Invoke(null, null); });
                    }
                    else
                    {
                        actions.Add(invokAtr.Stage, new List<Action>() { () => { function.Invoke(null, null); } });
                    }
                }
            }
        }
    }

}